﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;

namespace Xiaov.SmartWeb.Application.SupCan
{
    public class ConvertToXml
    {
        /// <summary>
        /// DataTable数据转换成XML供硕正控件使用
        /// </summary>
        /// <param name="dt">数据集</param>
        /// <param name="dataString">字段名</param>
        /// <param name="nStart">本页起始行</param>
        /// <param name="nRows">每页显示记录数</param>
        public static void Convert(DataTable dt, string dataString, int nStart, int nRows)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "text/xml";
            System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
            System.Web.HttpContext.Current.Response.CacheControl = "no-cache";
            StringBuilder sbStr = new StringBuilder(); //用来存储下面生成的xml
            // 生成xml数据
            sbStr.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?> <data totalrows=\"" + dt.Rows.Count.ToString() + "\">");
            if (dt.Rows.Count > 0)
            {
                //从数据库读取数据 循环添加至XML
                string[] columnName = dataString.Split(',');
                for (int i = nStart; i < dt.Rows.Count; i++)
                {
                    if (i - nStart >= nRows) break;
                    sbStr.Append("<record>");
                    for (int j = 0; j < columnName.Length; j++)
                    {
                        sbStr.Append("<" + columnName[j] + ">");
                        switch (dt.Rows[i][columnName[j]].GetType().ToString())
                        {
                            case "System.DBNull":
                                sbStr.Append(string.Empty);
                                break;
                            default:
                                sbStr.Append("<![CDATA[");
                                sbStr.Append(dt.Rows[i][columnName[j]].ToString());
                                sbStr.Append("]]>");
                                break;
                        }
                        sbStr.Append("</" + columnName[j] + ">");
                    }
                    sbStr.Append("</record>");
                }
            }
            sbStr.Append("</data>");
            //输出数据                 
            System.Web.HttpContext.Current.Response.Write(sbStr.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
    }
}